import { createRouter, createWebHistory } from 'vue-router'
import Home from '../views/Home.vue'
import AdminPage from '../views/AdminPage.vue'

/**
 * 应用路由配置
 */
const routes = [
  {
    path: '/',
    name: 'Home',
    component: Home
  },
  {
    path: '/search',
    name: 'Search',
    component: () => import('../views/Search.vue')
  },
  {
    path: '/latest',
    name: 'Latest',
    component: () => import('../views/Latest.vue')
  },
  {
    path: '/popular',
    name: 'Popular',
    component: () => import('../views/Popular.vue')
  },
  {
    path: '/admin',
    name: 'Admin',
    component: AdminPage,
    meta: {
      requiresAuth: true
    }
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

// 导航守卫确保在导航前加载认证状态
router.beforeEach(async (to, from, next) => {
  // 检查是否已经初始化认证状态
  if (window.$auth) {
    // 如果要访问的路由需要认证
    if (to.matched.some(record => record.meta.requiresAuth)) {
      // 等待认证初始化完成
      try {
        await window.$auth.authInitPromise
        // 检查用户是否已登录
        if (!window.$auth.isAuthenticated.value && !localStorage.getItem('auth_token')) {
          console.log('路由守卫: 未登录，重定向到登录页')
          next() // 仍然跳转到目标页面，但会显示登录表单
        } else {
          console.log('路由守卫: 已登录，允许访问')
          next()
        }
      } catch (error) {
        console.error('认证初始化失败:', error)
        next()
      }
    } else {
      next()
    }
  } else {
    // 如果认证系统尚未初始化完成，继续导航
    console.log('路由守卫: 认证系统未初始化，允许访问')
    next()
  }
})

export default router 